package com.chenju.invokechainservice.test;

import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
// 其他需要的类

public class PointcutParser {

    public void parsePointcutExpression(String pointcutExpression, Class<?> targetClass) {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(pointcutExpression);

        MethodMatcher methodMatcher = pointcut.getMethodMatcher();

        // 这里可以遍历目标类的方法，判断是否匹配切点表达式
        Method[] methods = targetClass.getDeclaredMethods();
        for (Method method : methods) {
            if (methodMatcher.matches(method, targetClass)) {
                System.out.println("Method " + method.getName() + " matches the pointcut expression.");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        File classFile = new File("D:\\Project\\springboot-easytest\\invokechain-service\\target\\classes\\com\\chenju\\invokechainservice\\test\\TestAopS.class");

        // 读取class文件的字节码
        byte[] classBytes = Files.readAllBytes(classFile.toPath());

        // 使用自定义的ClassLoader加载类
        Class<?> targetClass = new CustomClassLoader().defineClass(classBytes);
        String pointcutExpression = "@annotation(com.chenju.invokechainservice.annotation.EnableAOP)";
        // Class<?> targetClass = MyTargetClass.class; // 替换成你要解析的目标类

        PointcutParser parser = new PointcutParser();
        parser.parsePointcutExpression(pointcutExpression, targetClass);
    }

    static class CustomClassLoader extends ClassLoader {
        public Class<?> defineClass(byte[] classBytes) {
            return defineClass(null, classBytes, 0, classBytes.length);
        }
    }
}

